import React, { useState,useEffect }  from "react";
import { observer } from 'mobx-react';
import { Link,useParams } from "react-router-dom";
import Skeleton from 'react-loading-skeleton'
import 'react-loading-skeleton/dist/skeleton.css'
import BookStore from '../stores/BookDataStore';
import { ABdiv,ABuldiv,ABerrdiv,ABh1,ABbtu,ABp1,ABp2 } from "../styles/HomeCss";

const AboutBookHeader = () => {
  return(
    <ABdiv className="aboutbook">
      <ABh1>书籍详情</ABh1>
      <Link to="/">
        <ABbtu>主页</ABbtu>
      </Link>
      <Link to="/Blog">
        <ABbtu>博客列表</ABbtu>
      </Link>
    </ABdiv>
  )
}

class ErrorBoundary extends React.Component {
    state = { 
        hasError: false,
        error: null,
    };
    
    static getDerivedStateFromError(error) {
        return { 
            hasError: true,
            error: error,
        };  
    }
    componentDidCatch(error, errorInfo) {
        console.error("Error caught by ErrorBoundary:", error, errorInfo);
    }
    handleRetry = () => {
        this.setState({ hasError: false });
        AboutBook.loadBooks();
    };
    
    render() {
        if (this.state.hasError) {
            return (
            <ABdiv>
              <AboutBookHeader/>
              <ABuldiv>
                <ABerrdiv>
                  <p>{this.state.error?.message}</p>
                  <ABbtu onClick={this.handleRetry}>
                      重试
                  </ABbtu>
                </ABerrdiv>
              </ABuldiv>
            </ABdiv>
            );
        }
        return this.props.children;
    }
}
  
const AboutBook = observer(() => {

  const {id} = useParams();
  const [fetchError, setFetchError] = useState(null);
      
      useEffect(() => {
          const loadBooks = async () => {
              try {
                  await BookStore.fetchBooksById(id);
                  setFetchError(null);
              } catch (error) {
                  setFetchError(error);
              }
          };
          loadBooks();
      }, [id]);
      if (fetchError) {
          throw fetchError;
      }
      if(BookStore.isLoading){
        return (
          <div>
            <AboutBookHeader/>
            <ABuldiv>
              <p><Skeleton width={200} baseColor="rgba(128, 128, 128, 0.2)" highlightColor="rgba(128, 128, 128, 0.4)"/></p>
              <p><Skeleton width={150} baseColor="rgba(128, 128, 128, 0.2)" highlightColor="rgba(128, 128, 128, 0.4)"/></p>
              <p><Skeleton count={3} baseColor="rgba(128, 128, 128, 0.2)" highlightColor="rgba(128, 128, 128, 0.4)"/></p>
            </ABuldiv>
          </div>
        );
      }

  return (  
    <div>
      <AboutBookHeader/>
        <ABuldiv>
          <ABp1>书籍名称：{BookStore.about.name}</ABp1>
          <ABp1>作者：{BookStore.about.author}</ABp1>
          <ABp2>备注：{BookStore.about.content}</ABp2>
        </ABuldiv>
    </div>
  );
});

export { ErrorBoundary as ABErrBoundary};
export default AboutBook;